package com.mobartisan.workinglunch.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobartisan.workinglunch.R;
import com.mobartisan.workinglunch.SnakeApplication;
import com.mobartisan.workinglunch.bean.AccountRecord;
import com.mobartisan.workinglunch.bean.UserBeen;
import com.mobartisan.workinglunch.bean.globalSetting;
import com.mobartisan.workinglunch.constants.Constants;
import com.mobartisan.workinglunch.listener.CallBackListenter;
import com.mobartisan.workinglunch.ui.activity.ChangePasswordActivity;
import com.mobartisan.workinglunch.ui.activity.LoginActivity;
import com.mobartisan.workinglunch.ui.activity.MainActivity;
import com.mobartisan.workinglunch.ui.base.BaseActivity;
import com.mobartisan.workinglunch.ui.base.BaseFragment;
import com.mobartisan.workinglunch.util.SharedPreferencesUtil;
import com.mobartisan.workinglunch.util.Utils;
import com.mobartisan.workinglunch.widget.CheckVersionThread;
import com.roughike.bottombar.BottomBarTab;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import rx.Subscriber;

import static com.mobartisan.workinglunch.R.id.bottomBar;
import static com.mobartisan.workinglunch.ui.activity.LoginActivity.loge;

/**
 * Created by L on 2017/4/26.
 */

public class PersonFragment extends BaseFragment {

    public static final String TAG = PersonFragment.class.getSimpleName();
    @Bind(R.id.common_title_title)
    TextView commonTitleTitle;
    @Bind(R.id.tv_account)
    TextView tvAccount;
    @Bind(R.id.name)
    RelativeLayout name;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_totalmoney)
    TextView tvTotalmoney;
    @Bind(R.id.rlt_changePassword)
    RelativeLayout rltChangePassword;
    @Bind(R.id.tv_versions)
    TextView tvVersions;
    @Bind(R.id.tv_version_point)
    public ImageView version_point;
    @Bind(R.id.bt_logout)
    Button btLogout;
    String account, personname, versions;
    double totalmoney;
    private static PersonFragment personFragment;
    String fullname;
    String money = "0";
    globalSetting setting=null;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    queryObjects();
                    break;
                case 1:
//                    version_point.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };
    @Bind(R.id.versionId)
    RelativeLayout versionId;

    public static PersonFragment getFragmetntA() {
        if (personFragment == null) {
            personFragment = new PersonFragment();
        }
        return personFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_person;
    }

    @Override
    protected void initView(View view) {
        account = SharedPreferencesUtil.getInstance().getStringValue("username");
        tvAccount.setText(account);
        commonTitleTitle.setText("个人信息");
        tvVersions.setText(getLocalVersion(getContext()));
        tvName.setText(fullname);
        tvTotalmoney.setText(money);
        if (Constants.isNewest){
            version_point.setVisibility(View.VISIBLE);
        }
        queryObjects();
        queryName();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        fullname = "";
//        money="0.0";
    }

    @Override
    protected void initData() {

    }

    public void queryObjects() {
        String userId = SharedPreferencesUtil.getInstance().getStringValue("username");
        BmobQuery<AccountRecord> query = new BmobQuery<AccountRecord>();
        query.addWhereEqualTo("userId", userId);
        query.sum(new String[]{"money"});
        query.findStatistics(AccountRecord.class, new QueryListener<JSONArray>() {
            @Override
            public void done(JSONArray ary, BmobException e) {
                if (e == null) {
                    if (ary != null) {
                        try {
                            JSONObject obj = ary.getJSONObject(0);
                            Log.e(TAG, "done:======== "+ary );
                            double sum = obj.getDouble("_sumMoney");//_(关键字)+首字母大写的列名
                            sum = Math.round(sum*100);
                            money = String.valueOf(sum/100);
                            if (sum == 0.0) {
                                tvTotalmoney.setText("0.0");
                            } else {
                                tvTotalmoney.setText(money);
                            }
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                            tvTotalmoney.setText("0.0");
                        }
                    } else {
                        tvTotalmoney.setText("0.0");
                    }
                } else {
                   // Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                    BaseActivity.loge(e,TAG);
                    //tvTotalmoney.setText("0.0");
                }
            }
        });
    }

    @OnClick({R.id.rlt_changePassword, R.id.bt_logout,R.id.versionId})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.rlt_changePassword:
                Intent intent2 = new Intent(getActivity(), ChangePasswordActivity.class);
                startActivity(intent2);
                break;
            case R.id.bt_logout:
                SharedPreferencesUtil.getInstance().clearStringValue("password");
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                BmobUser.logOut();
                SnakeApplication.mainActivity.getActivity().finish();
                break;
            case R.id.versionId:
                if (Utils.isFastClick()){
                    getVersionName();
                }
                break;
        }
    }
    public String getVersionName() {
        final String[] network_VersionName = new String[1];
        final BmobQuery<globalSetting> bmobQuery = new BmobQuery<globalSetting>();
        //bmobQuery.setLimit(2);
//        bmobQuery.order("createdAt");
//        //先判断是否有缓存
//        boolean isCache = bmobQuery.hasCachedResult(AccountRecord.class);
//        if(isCache){
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);	// 先从缓存取数据，如果没有的话，再从网络取。
//        }else{
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);	// 如果没有缓存的话，则先从网络中取
//        }
//		observable形式
        bmobQuery.findObjectsObservable(globalSetting.class)
                .subscribe(new Subscriber<List<globalSetting>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        loge(e,TAG);
                    }

                    @Override
                    public void onNext(List<globalSetting> persons) {
                        //log("查询成功：共"+persons.size()+"条数据。");
                        //ToastUtils.showShort("查询成功：共" + persons.size() + "条数据。");
                        //给数据重新排序
                        setting = persons.get(0);
                        network_VersionName[0] =setting.getCurrentversion();
                        Constants.isCheckout=true;
                        CheckVersionThread versionThread =new  CheckVersionThread(getActivity(), setting, new CallBackListenter() {
                            @Override
                            public void onCallBack() {
                                if (Constants.isChickVersion){
                                    version_point.setVisibility(View.VISIBLE);
                                    SnakeApplication.mainActivity.handler.sendEmptyMessage(0);
                                    Constants.isNewest = true;
                                }else {
                                    version_point.setVisibility(View.INVISIBLE);
                                    SnakeApplication.mainActivity.handler.sendEmptyMessage(1);
                                    Constants.isNewest = false;
                                }
                            }
                        });
                        versionThread.compareVersionCode();

                    }
                });
//		bmobQuery.findObjects(new FindListener<Person>() {
//
//			@Override
//			public void done(List<Person> object, BmobException e) {
//				if(e==null){
//					toast("查询成功：共"+object.size()+"条数据。");
//					for (Person person : object) {
//						Log.d(TAG, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ");
//						Log.d(TAG, "ObjectId = "+person.getObjectId());
//						Log.d(TAG, "Name = "+person.getName());
//						Log.d(TAG, "Age = "+person.getAge());
//						Log.d(TAG, "Address = "+person.getAddress());
//						Log.d(TAG, "Gender = "+person.isGender());
//						Log.d(TAG, "CreatedAt = "+person.getCreatedAt());
//						Log.d(TAG, "UpdatedAt = "+person.getUpdatedAt());
//					}
//				}else{
//					loge(e);
//				}
//			}
//		});
        return network_VersionName[0];
    }


    /**
     * 获取应用程序版本（versionName）
     *
     * @return 当前应用的版本号
     */

    private String getLocalVersion(Context context) {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "获取应用程序版本失败，原因：" + e.getMessage());
            return "1.0.0";
        }

        return info.versionName;
    }

    public void queryName() {
        String username = SharedPreferencesUtil.getInstance().getStringValue("username");
        final BmobQuery<UserBeen> bmobQuery = new BmobQuery<UserBeen>();
        bmobQuery.addWhereEqualTo("username", username);

        bmobQuery.findObjectsObservable(UserBeen.class)
                .subscribe(new Subscriber<List<UserBeen>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        loge(e,TAG);
                    }

                    @Override
                    public void onNext(List<UserBeen> persons) {
                        //log("查询成功：共"+persons.size()+"条数据。");
                        //给数据重新排序
                        UserBeen userBeen = persons.get(0);
                        fullname = userBeen.getFullname();
                        tvName.setText(fullname);
                    }
                });
//		bmobQuery.findObjects(new FindListener<Person>() {
//
//			@Override
//			public void done(List<Person> object, BmobException e) {
//				if(e==null){
//					toast("查询成功：共"+object.size()+"条数据。");
//					for (Person person : object) {
//						Log.d(TAG, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ");
//						Log.d(TAG, "ObjectId = "+person.getObjectId());
//						Log.d(TAG, "Name = "+person.getName());
//						Log.d(TAG, "Age = "+person.getAge());
//						Log.d(TAG, "Address = "+person.getAddress());
//						Log.d(TAG, "Gender = "+person.isGender());
//						Log.d(TAG, "CreatedAt = "+person.getCreatedAt());
//						Log.d(TAG, "UpdatedAt = "+person.getUpdatedAt());
//					}
//				}else{
//					loge(e);
//				}
//			}
//		});
    }
}
